﻿using UnityEngine;
using System.Collections;

public class Mir : MonoBehaviour {
    AudioClip record;
    string devices;
    public float sound;
    public float power;
    public int soundLength;

	// Use this for initialization
	void Start () {
        devices = Microphone.devices[0];
        record = Microphone.Start(devices, true, 999, 44100);
	}
	
	// Update is called once per frame
	void Update () {
        sound = GetMaxVolume() * power;
	}

    float GetMaxVolume()
    {
        float maxVolume = 0f;
        float[] volumeData = new float[soundLength];
        int offset = Microphone.GetPosition(devices) - soundLength + 1;
        if (offset < 0)
        {
            return 0;
        }
        record.GetData(volumeData, offset);
        for (int i = 0; i < soundLength; i++)
        {
            float tempMax = volumeData[i];
            if (maxVolume < tempMax)
            {
                maxVolume = tempMax;
            }
        }

        return maxVolume;
    }
}
